package com.adnaan.backend.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.adnaan.backend.common.event.BaseEvent;
import com.adnaan.backend.common.event.EventType;
import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.entity.Goods;
import com.adnaan.backend.entity.Order;
import com.adnaan.backend.entity.vo.OrderVo;
import com.adnaan.backend.mapper.OrderMapper;
import com.adnaan.backend.service.GoodsService;
import com.adnaan.backend.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private GoodsService goodsService;

    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(Long userId, OrderVo orderVo) {
        // 检查商品是否存在
        Goods goods = goodsService.getById(orderVo.getGoodsId());
        if (goods == null) {
            throw new ServicesException("商品不存在");
        }

        // 检查库存
        if (!goodsService.checkStock(orderVo.getGoodsId(), orderVo.getQuantity())) {
            throw new ServicesException("库存不足");
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setGoodsId(orderVo.getGoodsId());
        order.setSupplierId(goods.getSupplierId());
        order.setQuantity(orderVo.getQuantity());
        order.setConsignee(orderVo.getConsignee());
        order.setMobile(orderVo.getMobile());
        order.setAddress(orderVo.getAddress());
        order.setRemark(orderVo.getRemark());
        order.setTotalAmount(goods.getPrice().multiply(new BigDecimal(orderVo.getQuantity())));
        order.setStatus(0);

        if (save(order)) {
            // 扣减库存
            goodsService.updateStock(orderVo.getGoodsId(), -orderVo.getQuantity());
            // 发布订单创建事件
            eventPublisher.publishEvent(new BaseEvent(this, order.getId(), order.getSupplierId(), EventType.ORDER_CREATE));
            return order.getId();
        }
        throw new ServicesException("创建订单失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        Order order = getById(id);
        if (order == null) {
            throw new ServicesException("订单不存在");
        }
        order.setStatus(status);
        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            throw new ServicesException("订单不存在");
        }

        if (order.getStatus() != 0) {
            throw new ServicesException("只能取消待支付的订单");
        }

        // 恢复库存
        goodsService.updateStock(order.getGoodsId(), order.getQuantity());

        order.setStatus(4);
        if (updateById(order)) {
            // 发布订单取消事件
            eventPublisher.publishEvent(new BaseEvent(this, order.getId(), order.getSupplierId(), EventType.ORDER_CANCEL));
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReceive(Long id) {
        Order order = getById(id);
        if (order == null) {
            throw new ServicesException("订单不存在");
        }

        if (order.getStatus() != 2) {
            throw new ServicesException("只能确认已发货的订单");
        }

        order.setStatus(3);
        return updateById(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelTimeoutOrders() {
        // 查询24小时前创建的未支付订单
        LocalDateTime timeoutTime = LocalDateTime.now().minusHours(24);
        List<Order> timeoutOrders = list(new LambdaQueryWrapper<Order>()
                .eq(Order::getStatus, 0)
                .lt(Order::getCreateTime, timeoutTime));

        if (timeoutOrders.isEmpty()) {
            return 0;
        }

        int count = 0;
        for (Order order : timeoutOrders) {
            try {
                // 恢复库存
                goodsService.updateStock(order.getGoodsId(), order.getQuantity());

                // 更新订单状态
                order.setStatus(4);
                if (updateById(order)) {
                    count++;

                    // 发布订单取消事件
                    eventPublisher.publishEvent(new BaseEvent(this, order.getId(), order.getSupplierId(), EventType.ORDER_CANCEL));
                }
            } catch (Exception e) {
                log.error("取消超时订单失败，订单ID：{}", order.getId(), e);
            }
        }
        return count;
    }

    @Override
    public String remind(Long id) {
        Order order = getById(id);
        if (order != null && order.getStatus() == 1) {
            // 发布订单提醒事件
            eventPublisher.publishEvent(new BaseEvent(this, order.getId(), order.getSupplierId(), EventType.ORDER_REMIND));
            return "订单提醒已发送";
        }
        return null;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "ORDER" + System.currentTimeMillis() + RandomUtil.randomNumbers(6);
    }
} 